package com.itlong.cloud.controller.sdkV2.intercom.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.operate.OperateDeviceManageGetPageDTO;
import com.itlong.cloud.POJO.DTO.property.*;
import com.itlong.cloud.POJO.DTO.sdk.*;
import com.itlong.cloud.POJO.PO.ProjectPO;
import com.itlong.cloud.POJO.PO.TimeTaskAuthDeviceAddressInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.SDKMessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeviceManageInfoAllVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeviceManageInfoVO;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.POJO.VO.sdk.CloudTalkDeviceListPageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.PropertyEquipTypeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.CloudTalkErrorCodeEnum;
import com.itlong.cloud.equip.operate.IOperateDeviceManageServiceClient;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.equip.sdk.ICloudTalkSDKServiceClient;
import com.itlong.cloud.equip.sdk.ISDKServerOldEquipServiceClient;
import com.itlong.cloud.project.property.IPropertyBuildInfoServiceClient;
import com.itlong.cloud.project.property.IPropertyUnitInfoServiceClient;
import com.itlong.cloud.project.sdk.ICloudTalkSDKServerProjectServiceClient;
import com.itlong.cloud.project.sdk.ISDKServerOldBuildServiceClient;
import com.itlong.cloud.project.sdk.ISDKServerOldProjectServiceClient;
import com.itlong.cloud.project.sdk.ISDKServerOldUnitServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.sdk.ICloudTalkSDKServerUserServiceClient;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.SetListUtil;
import com.itlong.cloud.utils.page.Page;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <desc>
 *      云对讲SDK服务端设备信息Controller
 * </desc>
 *
 * @createDate 2018/05/14
 */
@RestController
@RequestMapping("/sdk/cloud/intercom/server")
public class SDKCloudTalkEquipController {

    private static Logger LOG = LoggerFactory.getLogger(SDKCloudTalkEquipController.class);

    @Autowired
    ISDKServerOldUserServiceClient iSDKUserServiceClient;

    @Autowired
    ISDKServerOldProjectServiceClient iSDKProjectServiceClient;

    @Autowired
    ISDKServerOldBuildServiceClient iSDKBuildServiceClient;

    @Autowired
    ISDKServerOldUnitServiceClient iSDKServerOldUnitServiceClient;

    @Autowired
    ISDKServerOldEquipServiceClient iSDKServerEquipServiceClient;

    @Autowired
    IPropertyEquipServiceClient iPropertyEquipServiceClient;


    @Autowired
    IOperateDeviceManageServiceClient iOperateDeviceManageServiceClient;

    @Autowired
    IPropertyUnitInfoServiceClient iPropertyUnitInfoServiceClient;

    @Autowired
    IPropertyBuildInfoServiceClient iPropertyBuildInfoServiceClient;

    @Autowired
    ICloudTalkSDKServerUserServiceClient iCloudTalkSDKServerUserServiceClient;

    @Autowired
    ICloudTalkSDKServiceClient iCloudTalkSDKServiceClient; //云对讲SDK服务接口

    @Autowired
    private ICloudTalkSDKServerProjectServiceClient iCloudTalkSDKServerProjectServiceClient;

    @Value("${" + PlatformConstants.COUD_TALK_PRODUCT_TYPEID + "}")
    public String COUD_TALK_PRODUCT_TYPEID;

    @Value("${" + PlatformConstants.CLOUDTALK_SDK_USER_TOKEN_KEY + "}")
    String CLOUDTALK_SDK_USER_TOKEN_KEY;


    /**
     * <desc>
     *     云对讲SDK添加云对讲设备
     * <desc/>
     * @return       MessageVO   标准格式化响应结果
     * @author JuGuang.S
     * @createDate 2018/05/14
     */
    @ResponseBody
    @PostMapping("/device/add")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_ADD_CLOUD_TALK_LOG_DESC)
    public Object sdkAddDevice() {

        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudTalkSDKServerSaveDeviceDTO saveDeviceDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerSaveDeviceDTO.class, request);

            JSONObject js = new JSONObject();

            String appId = saveDeviceDTO.getAppId();
            String projectId = saveDeviceDTO.getProjectId();
            String deviceUnique = saveDeviceDTO.getDeviceUnique();
            String deviceJson = saveDeviceDTO.getDeviceJson();
            String smartType = saveDeviceDTO.getSmartType();
            String responseTimestamp = new Date().getTime()+"";
            saveDeviceDTO.setResponseTimestamp(responseTimestamp);
            saveDeviceDTO.setAppSecret(request.getAttribute("appSecret").toString());

            LOG.info("====SDK添加设备入参：appId：" + appId + " projectId:" + projectId + " deviceUnique:" + deviceUnique + " deviceJson:" + deviceJson + "smartType:" + smartType);
            //projectId = DesEncryptUtil.projectIdDesEncrypt(projectId) == null ? projectId : DesEncryptUtil.projectIdDesEncrypt(projectId);
            if (StringUtils.isEmpty(projectId) || StringUtils.isEmpty(appId) || StringUtils.isEmpty(deviceJson) || StringUtils.isEmpty(smartType)) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),saveDeviceDTO.getRequestId(),responseTimestamp,"");
            }

            ProjectPO projectInfo = iSDKProjectServiceClient.getByProjectId(projectId);
            if (projectInfo == null) {
                return new SDKMessageVO(CloudTalkErrorCodeEnum.PROJECT_NOT_EXIST.getErrorCode(),saveDeviceDTO.getRequestId(),responseTimestamp,"");
            }

            // 校验开发者账号是否有该项目的权限
            List<String> projectIdList = iCloudTalkSDKServerUserServiceClient.getProjectIdByParams(appId);
            String projectStr = null;
            if(!projectIdList.isEmpty() && projectIdList!=null){
                projectStr = String.join(",",projectIdList);
            }
            if(!projectStr.contains(projectId)){
                return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_CHECKDEVELOPER_AUTH.getErrorCode(),saveDeviceDTO.getRequestId(),responseTimestamp,"");
            }

            //解析deviceJson
            SDKEquipSaveDTO addEquip = JSONObject.parseObject(deviceJson, SDKEquipSaveDTO.class);
            if (addEquip == null) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode(), String.format("%s:%s", "解析deviceJson数据异常", deviceJson));
            }
            addEquip.setProjectId(projectId);
            //设备数据校验
            Object message = this.checkEquip(addEquip);
            if (message != null) {
                return message;
            }

            String[] buildIdArr = null;
            String[] unitIdArr = null;
            String buildIds = addEquip.getBuildIds();
            String unitIds = addEquip.getUnitIds();
            if (StringUtils.isNotEmpty(buildIds)) {
                buildIdArr = buildIds.split(",");
            }
            if (StringUtils.isNotEmpty(unitIds)) {
                unitIdArr = unitIds.split(",");
            }

            int deviceType = 3;
            String deviceName = addEquip.getDeviceName();
            String deviceStatus = addEquip.getDeviceStatus();

            //默认添加或更新设备的状态是 1-启用
            Integer status = StringUtils.isEmpty(deviceStatus)?DataStatusEnum.NORMAL.getType() : Integer.parseInt(deviceStatus);

            String sipAccount = null;
            //添加或更新设备
            if (StringUtils.isEmpty(deviceUnique)) {

                Set<String> unitIdSet = new HashSet<>();
                //处理改变的设备地址给权限队列
                if (unitIdArr != null) {
                    //1栋多单元
                    unitIdSet.addAll(Arrays.asList(unitIdArr));
                } else {
                    //多栋
                    Set<String> buildIdSet = new HashSet<>();
                    buildIdSet.addAll(Arrays.asList(buildIdArr));
                    List<String> unitIdList = iPropertyUnitInfoServiceClient.getUnitIdInBuildIds(String.join(",", buildIdSet));
                    unitIdSet.addAll(unitIdList);

                }

                //deviceUnique 为空时，添加设备
                //设备名称重复性校验
                PropertyEquipGetDTO deviceNameCheck = new PropertyEquipGetDTO(projectId);
                deviceNameCheck.setDeviceType(deviceType);
                deviceNameCheck.setDeviceName(deviceName);
                List<PropertyEquipGetVO> deviceNameCheckVOS = iPropertyEquipServiceClient.checkEquip(deviceNameCheck);
                if (deviceNameCheckVOS != null && !deviceNameCheckVOS.isEmpty()) {
                    return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_ADD_EQUIP_NAME_IS_EXIST.getErrorCode(),saveDeviceDTO.getRequestId(),responseTimestamp,"");
                }

                //查询该类型设备的最大deviceId,拼接deviceUnique
                Map<String, Object> getMaxDeviceId = new HashMap<>();
                getMaxDeviceId.put("projectId", projectId);
                getMaxDeviceId.put("deviceType", deviceType);
                Integer maxDeviceId = iSDKServerEquipServiceClient.getMaxDeviceId(getMaxDeviceId);

                String deviceId = String.format("%04d", maxDeviceId + 1);
                deviceUnique = String.format("%s%d%s", projectId, deviceType, deviceId);
                PropertyCloudIntercomSaveDTO equipAddDTO = new PropertyCloudIntercomSaveDTO(projectId, deviceUnique, deviceType,
                        deviceId, deviceName, buildIds, unitIds);
                equipAddDTO.setSmartType(Integer.parseInt(smartType));

                //云对讲设备其他参数预处理：包含生成Sn规则
                equipAddDTO = this.cloudIntercomeHandle(equipAddDTO);
                js.put("sn",equipAddDTO.getSn());

                //地址发生变化，将变化的地址存储的到定时任务表中
                Date date = new Date();
                TimeTaskAuthDeviceAddressInfoPO deviceAddrPO = new TimeTaskAuthDeviceAddressInfoPO(projectId,
                        appId, String.join(",", unitIdSet),
                        DataStatusEnum.NORMAL.getType(), date, date);
                deviceAddrPO.setDeviceUniques(deviceUnique);
                equipAddDTO.setTimeTaskAuthDeviceAddressInfoPO(deviceAddrPO);
                equipAddDTO.setProductTypeId(COUD_TALK_PRODUCT_TYPEID);

                iPropertyEquipServiceClient.addPropertyEquip(equipAddDTO);
                //根据设备唯一码查询云对讲sip账号
                PropertyEquipGetVO oldEquip = iPropertyEquipServiceClient.getByDeviceUnique(deviceUnique);
                if (oldEquip == null) {
                    return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_ADD_DEVICEUNIQUE_IS_NOTEXIST.getErrorCode(),saveDeviceDTO.getRequestId(),responseTimestamp,"");
                }
                sipAccount = oldEquip.getSipAccount();
                //保存生成操作日志所需信息 详细描述和接口类别
                request.setAttribute("remark",String.format("%s%s%s","添加设备唯一码：",deviceUnique,"的设备"));
                request.setAttribute("portType",LogDescConstant.SDK_CLOUD_TALK_TYPE_LOG_DESC);

            } else {
                //解码deviceUnique,更新设备
                //deviceUnique = DesEncryptUtil.projectIdDesEncrypt(deviceUnique);
                PropertyEquipGetVO oldEquip = iPropertyEquipServiceClient.getByDeviceUnique(deviceUnique);
                js.put("sn",oldEquip.getSn());
                if (oldEquip == null) {
                    return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_ADD_DEVICEUNIQUE_IS_NOTEXIST.getErrorCode(),saveDeviceDTO.getRequestId(),responseTimestamp,"");
                }
                sipAccount = oldEquip.getSipAccount();

                //设备名称重复性校验
                PropertyEquipGetDTO deviceNameCheck = new PropertyEquipGetDTO(projectId);
                deviceNameCheck.setDeviceType(deviceType);
                deviceNameCheck.setDeviceName(deviceName);
                deviceNameCheck.setDeviceUnique(deviceUnique);
                List<PropertyEquipGetVO> deviceNameCheckVOS = iPropertyEquipServiceClient.checkEquip(deviceNameCheck);
                if (deviceNameCheckVOS != null && !deviceNameCheckVOS.isEmpty()) {
                    return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_ADD_EQUIP_NAME_IS_EXIST.getErrorCode(),saveDeviceDTO.getRequestId(),responseTimestamp,"");
                }
                PropertyCloudIntercomSaveDTO equipAddDTO = new PropertyCloudIntercomSaveDTO(projectId, deviceUnique, deviceType,
                        null, deviceName, buildIds, unitIds);
                equipAddDTO.setSmartType(Integer.parseInt(smartType));
                equipAddDTO.setStatus(status);
                //找到变化后地址转化为unitId的差集
                Set<String> newUnitIdSet = new HashSet<>();
                List<String> newBuildIdList = new ArrayList<>();
                if (buildIdArr != null && buildIdArr.length > 0) {
                    for (String buildId : buildIdArr) {
                        if (unitIdArr != null && unitIdArr.length > 0) {
                            newUnitIdSet.addAll(Arrays.asList(unitIdArr));
                        } else {
                            newBuildIdList.add(buildId);
                        }
                    }
                    if (!newBuildIdList.isEmpty()) {
                        List<String> unitIdList = iPropertyUnitInfoServiceClient.getUnitIdInBuildIds(String.join(",", newBuildIdList));
                        newUnitIdSet.addAll(unitIdList);
                    }
                }
                //获取旧地址转化为单元ID后的集合
                Set<String> oldUnitIdSet = this.getEquipOldUnitId(deviceUnique);
                Set<String> diffUnitIdSet = SetListUtil.getDiffSet(oldUnitIdSet, newUnitIdSet);

                if (!diffUnitIdSet.isEmpty()) {
                    Date date = new Date();
                    TimeTaskAuthDeviceAddressInfoPO deviceAddrPO = new TimeTaskAuthDeviceAddressInfoPO(projectId,
                            appId, String.join(",", diffUnitIdSet),
                            DataStatusEnum.NORMAL.getType(), date, date);
                    deviceAddrPO.setDeviceUniques(deviceUnique);
                    equipAddDTO.setTimeTaskAuthDeviceAddressInfoPO(deviceAddrPO);
                } else {
                    //如果设备地址未发生变化，但设备名称发生变化，需要查找所影响的住户，并刷新缓存
                    if (!deviceName.equals(oldEquip.getDeviceName())) {
                        equipAddDTO.setIsOnlyNameChange(true);
                    } else {
                        equipAddDTO.setIsOnlyNameChange(false);
                    }
                }
                iPropertyEquipServiceClient.updatePropertyEquip(equipAddDTO);
                //保存生成操作日志所需信息 详细描述和接口类别
                request.setAttribute("remark",String.format("%s%s%s","更新设备唯一码：",deviceUnique,"的设备信息"));
                request.setAttribute("portType",LogDescConstant.SDK_CLOUD_TALK_TYPE_LOG_DESC);
            }

            //根据项目编号查询sip的ip和端口号
            Map<String,Object> map = iCloudTalkSDKServerProjectServiceClient.getSipInfoByProjectId(projectId);

            String sipAccountData = null;
            if(map.size()>0){
                sipAccountData = String.format("%s@%s:%s",sipAccount,map.get("sipAddress"),map.get("sipPort"));
            }

            js.put("deviceUnique", deviceUnique);
            js.put("deviceName", deviceName);
            js.put("sipAccount",sipAccountData);

            Map<String, Object> signMap = new HashMap<>();
            signMap.put("data", new JSONObject(js));//签名使用json格式内容进行
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), request.getAttribute("requestId").toString(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(signMap,request.getAttribute("requestId").toString(),responseTimestamp, saveDeviceDTO.getAppSecret()), js);
        } catch (Exception e) {
            throw new DataAccessException("【SDK服务端_SDKServerOldEquipController_sdkAddDevice】添加更新设备异常", e);
        }
    }
    
    
    /**
     * <desc>
     *      添加设备前的参数校验
     * <desc/>
     * @param   addEquip  添加的设备实体
     * @return MessageVO   标准格式化响应结果
     * @author JuGuang.S
     * @createDate 2018/05/14
     */
    public Object checkEquip(SDKEquipSaveDTO addEquip) {

        String buildNum = addEquip.getBuildNum();
        String unitNum = addEquip.getUnitNum();
        if (StringUtils.isEmpty(buildNum)) {
            return new MessageVO(CloudTalkErrorCodeEnum.SERVER_ADD_EQUIP_BUID.getErrorCode());
        }

        //根据楼栋单元编号获取楼栋单元ID
        Map<String, String> params = new HashMap<>();
        params.put("projectId", addEquip.getProjectId());
        params.put("buildNumIn", buildNum);
        String buildIds = iSDKBuildServiceClient.getBuildIdsByParams(params);
        String unitIds ="";
        if (StringUtils.isEmpty(buildIds)) {
            return new MessageVO(CloudTalkErrorCodeEnum.SERVER_ADD_EQUIP_BUID_UNIT.getErrorCode());
        }
        String[] buildIdArr = buildIds.split(",");

        if (StringUtils.isNotEmpty(unitNum)) {
            Map<String, String> param = new HashMap<>();
            param.put("buildId", buildIdArr[0]);
            param.put("unitNumIn", unitNum);
            unitIds = iSDKServerOldUnitServiceClient.getUnitIdsByParams(param);
            if (StringUtils.isNotEmpty(unitIds)) {
                addEquip.setUnitIds(unitIds);
            }
        }

        //有单元的时候，楼栋必须为1栋
        if (StringUtils.isNotEmpty(unitIds) && buildIdArr.length != 1) {
            return new MessageVO(CloudTalkErrorCodeEnum.SERVER_ADD_EQUIP_BUID_UNIT.getErrorCode());
        }
        addEquip.setBuildIds(String.join(",",buildIdArr));
        return null;
    }


    /**
     * <desc>
     *      根据设备唯一码查询设备归属地址，并精确到unitId
     * <desc/>
     * @param   deviceUnique    待查询的设备唯一码
     * @return 归属地精确到小区后的unitId集合
     * @author JuGuang.S
     * @createDate 2018/05/14
     */
    private Set<String> getEquipOldUnitId(String deviceUnique) {
        List<PropertyEquipAddressVO> oldEquipAddress = iPropertyEquipServiceClient.getEquipAddress(deviceUnique);
        Set<String> oldUnitIdSet = new HashSet<>();
        if (oldEquipAddress != null && !oldEquipAddress.isEmpty()) {
            List<String> oldBuildIdList = new ArrayList<>();
            oldEquipAddress.forEach(oldAdress -> {
                List<PropertyProjectUnitSimpleInfoVO> units = oldAdress.getUnits();
                if (units != null && !units.isEmpty()) {
                    for (PropertyProjectUnitSimpleInfoVO unit : units) {
                        oldUnitIdSet.add(unit.getUnitId());
                    }
                } else {
                    oldBuildIdList.add(oldAdress.getBuildId());
                }
            });
            if (!oldBuildIdList.isEmpty()) {
                oldUnitIdSet.addAll(iPropertyUnitInfoServiceClient.getUnitIdInBuildIds(String.join(",", oldBuildIdList)));
            }
        }
        return oldUnitIdSet;
    }

    /**
     * <desc>
     * 对云对讲相关的预处理
     * <desc/>
     *
     * @param cloudIntercomSaveDTO 处理前的数据传输对象
     * @return PropertyEquipSaveDTO    处理后的数据传输对象
     * @author JuGuang.S
     * @createDate 2018/05/15
     */
    private PropertyCloudIntercomSaveDTO cloudIntercomeHandle(PropertyCloudIntercomSaveDTO cloudIntercomSaveDTO) throws Exception {

        //拼接sn
        String[] buildIdArr = null;
        String[] unitIdArr = null;
        String buildIds = cloudIntercomSaveDTO.getBuildIds();
        String unitIds = cloudIntercomSaveDTO.getUnitIds();
        if (StringUtils.isNotEmpty(buildIds)) {
            buildIdArr = buildIds.split(",");
        }
        if (StringUtils.isNotEmpty(unitIds)) {
            unitIdArr = unitIds.split(",");
        }
        String buildNum = "000";
        String unitNum = "00";
        String projectId = cloudIntercomSaveDTO.getProjectId();

        //围墙机的SN后面buildNum和unitNum 全为0,门口机分情况考虑
        if (cloudIntercomSaveDTO.getSmartType() == PropertyEquipTypeEnum.CLOUD_INTERCOM_ENTRANCE.getType()) {
            if (unitIdArr != null && unitIdArr.length == 1) {
                PropertyProjectGetUnitInfoDTO unitDTO = new PropertyProjectGetUnitInfoDTO(unitIds);
                PropertyProjectUnitInfoVO oneUnitInfo = iPropertyUnitInfoServiceClient.getOneUnitInfo(unitDTO);
                if (oneUnitInfo != null) {
                    unitNum = oneUnitInfo.getUnitNum();
                    buildNum = oneUnitInfo.getBuildNum();
                }
            }
            if ("000".equals(buildNum) && buildIdArr != null && buildIdArr.length == 1) {
                PropertyProjectGetBuildInfoDTO buildDTO = new PropertyProjectGetBuildInfoDTO(buildIds);
                PropertyProjectBuildInfoVO oneBuildInfo = iPropertyBuildInfoServiceClient.getOneBuildInfo(buildDTO);
                if (null != oneBuildInfo) {
                    buildNum = oneBuildInfo.getBuildNum();
                }
            }
        }
        cloudIntercomSaveDTO.setSn(String.format("%s%s%s%03d", cloudIntercomSaveDTO.getProjectId(), buildNum, unitNum, Integer.parseInt(cloudIntercomSaveDTO.getDeviceId())));

        return cloudIntercomSaveDTO;
    }

    /**
     * <desc>
     *      获取云对将设备列表。
     * <desc/>
     *
     * @param  * @param null
     * @return
     * @author shengen.T
     * @createDate 2018-05-17
     */
    @UnAuthAccessRequired
    public Object getCloudTalkDeviceList(CloudDeviceSDKDTO cloudDeviceSDKDTO){
        SDKMessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudTalkDeviceGetPageDTO pageDTO = new CloudTalkDeviceGetPageDTO();
            BeanUtils.copyProperties(cloudDeviceSDKDTO,pageDTO);
            String appId = pageDTO.getAppId();
            String projectId = pageDTO.getProjectId();
            String responseTimestamp = new Date().getTime()+"";
            pageDTO.setResponseTimestamp(responseTimestamp);
            if (projectId == null || StringUtils.isEmpty(appId)) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),pageDTO.getRequestId(),responseTimestamp,"");
            }
            pageDTO.setProjectId(projectId);
            // 校验开发者账号是否有该项目的权限
            List<String> projectIdList = iCloudTalkSDKServerUserServiceClient.getProjectIdByParams(appId);
            String projectStr = null;
            if(!projectIdList.isEmpty() && projectIdList!=null){
                projectStr = String.join(",",projectIdList);
            }
            if(!projectStr.contains(projectId)){
                return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_CHECKDEVELOPER_AUTH.getErrorCode(),pageDTO.getRequestId(),responseTimestamp,"");
            }
            pageDTO.setProjectId(projectId);
            LOG.info("======getCloudTalkDeviceList获取云对将设备列表============入参================>{}",null==pageDTO?"":pageDTO.toString());

            Page<CloudTalkDeviceListPageVO> pageVO = iCloudTalkSDKServiceClient.getCloudTalkDeviceList(pageDTO);
//            Map<String,Object> map = new HashMap<>();
//            map.put("totalNumber",pageVO.getPage().getTotalNumber());
//            map.put("deviceArr",pageVO.getRows());
            Map<String, Object> signMap = new HashMap<>();
            signMap.put("data", JSON.toJSONString(pageVO));
            LOG.info("======getCloudTalkDeviceList获取云对将设备列表============出参================>{}",signMap.toString());

            messageVO = new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), pageDTO.getRequestId(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(signMap,pageDTO.getRequestId(),responseTimestamp, request.getAttribute("appSecret").toString()), pageVO);
        }catch (Exception e){
            throw new DataAccessException("【云对讲SDK服务端】获取项目云对讲设备列表",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     * 获取设备在线状态 设备类型：1云对讲 3人脸平板  7一体式人脸识别仪
     * </desc>
     *
     * @Author chengshican
     * @Date 2020-09-23 19:09
     * @Param
     * @Return
     * @Exception
     */

   @UnAuthAccessRequired
    public Object getCloudTalkAppStatus(CloudDeviceSDKDTO dto) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        List<String> paramList=null;
        if (dto.getDeviceUnique().length()!=0){
            paramList=Arrays.asList(dto.getDeviceUnique());
        }
        Map<String, Object> paramMap = new HashMap<>();
        for(String a :paramList){
            paramMap.put(a,a);
        }
        try {
            //传入设备id，一个或者多个，和设备类型 一体式人脸识别平板
            OperateDeviceManageGetPageDTO operateDeviceManageGetPageDTO = new OperateDeviceManageGetPageDTO();
            operateDeviceManageGetPageDTO.setDeviceUnique(dto.getDeviceUnique());
            operateDeviceManageGetPageDTO.setDeviceType(dto.getDeviceType());
            LOG.info("======getCloudTalkAppStatus获取设备在线状态============入参================>{}",operateDeviceManageGetPageDTO.toString());

            OperateDeviceManageInfoAllVO deviceByPage = iOperateDeviceManageServiceClient.getDeviceByPage(operateDeviceManageGetPageDTO);
            Page<OperateDeviceManageInfoVO> page = deviceByPage.getPage();
            if (page.getRows().size()!=0){
                List<OperateDeviceManageInfoVO> rows = page.getRows();
                for (OperateDeviceManageInfoVO OperateDeviceManageInfoVO : rows) {
                    Map<String, Object> map = new HashMap<>();
                    if (paramMap.containsKey(OperateDeviceManageInfoVO.getDeviceUnique())){
                        map.put("deviceName",OperateDeviceManageInfoVO.getDeviceName());
                        map.put("deviceUnique",OperateDeviceManageInfoVO.getDeviceUnique());
                        map.put("isOnline",OperateDeviceManageInfoVO.getIsOnline());
                        list.add(map);
                    }

                }

            }


        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_云对讲getCloudTalkAppStatus】获取在线状态失败", e);
        }
        Map<String, Object> signMap = new HashMap<>();
        signMap.put("data", JSON.toJSONString(list));
       LOG.info("======getCloudTalkAppStatus获取设备在线状态============出参================>{}",signMap.toString());

       return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                Md5EncryptUtil.getSDKV2Md5(signMap, dto.getRequestId(), dto.getResponseTimestamp(), dto.getAppSecret()), list);
    }
}